package org.yoki.edu.portal.core.trace.domain;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.yunzhitx.cloud.common.model.PageResult;
import com.yunzhitx.cloud.common.model.ddd.AbstractEntity;
import com.yunzhitx.cloud.common.model.ddd.InstanceFactory;
import com.yunzhitx.cloud.common.model.exception.Shift;
import lombok.Data;

import org.yoki.edu.common.utils.geometry.Circle;
import org.yoki.edu.common.utils.geometry.GeometryUtils;
import org.yoki.edu.common.utils.geometry.Point;
import org.yoki.edu.portal.core.exception.BasicRestStatus;
import org.yoki.edu.portal.core.trace.infra.TraceTrajectoryRepository;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.persistence.Column;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.List;

/**
 * 代码生成器自动生成
 * Date:2018-2-7 9:18:22
 *
 * @author
 */
@Data
@Table(name = "tra_trace_trajectory")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TraceTrajectory extends AbstractEntity<TraceTrajectoryRepository> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 用户ID
     */
    @Column(name = "fd_userId")
    private Integer userId;
    /**
     * 用户设备MAC
     */
    @Column(name = "fd_userMac")
    private String userMac;
    /**
     * 年月日，如：20180101
     */
    @Column(name = "fd_date")
    private Integer date;
    /**
     * 时分秒，如：090101
     */
    @Column(name = "fd_time")
    private Integer time;
    /**
     * 经纬度线路(预留)
     */
    @Column(name = "fd_route")
    private String route;
    /**
     * xy线路(预留)
     */
    @Column(name = "fd_xYroute")
    private String xYroute;
    /**
     * 备注
     */
    @Column(name = "fd_remark")
    private String remark;

    public TraceTrajectory() {
    }

    public TraceTrajectory(Integer id) {
        setId(id);
    }

    @Override
    public Serializable getKey() {
        return getId();
    }

    @Override
    public boolean existed() {
        return false;
    }

    private static TraceTrajectoryRepository traceTrajectoryRepository;

    public static TraceTrajectoryRepository getTraceTrajectoryRepository() {
        if (null == traceTrajectoryRepository) {
            traceTrajectoryRepository = InstanceFactory.getInstance(TraceTrajectoryRepository.class);
        }
        return traceTrajectoryRepository;
    }

    public static Boolean existedByDate(String userMac, Integer date, Integer time) {
        Example e = new Example(TraceTrajectory.class);
        if (StringUtil.isEmpty(userMac)) {
            userMac = null;
        }
        if (null == date) {
            date = null;
        }
        if (null == time) {
            time = null;
        }
        e.createCriteria().andEqualTo("userMac", userMac)
                .andEqualTo("date", date)
                .andEqualTo("time", time);
        Integer count = getTraceTrajectoryRepository().selectCountByExample(e);
        if (null != count && count > 0) {
            return true;
        }
        return false;
    }

    public static TraceTrajectory findExistedByDate(String userMac, Integer date, Integer time) {
        Example e = new Example(TraceTrajectory.class);
        if (StringUtil.isEmpty(userMac)) {
            userMac = null;
        }
        if (null == date) {
            date = null;
        }
        if (null == time) {
            time = null;
        }
        e.createCriteria().andEqualTo("userMac", userMac)
                .andEqualTo("date", date)
                .andEqualTo("time", time);
        List<TraceTrajectory> list = getTraceTrajectoryRepository().selectByExample(e);
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /* ************************************************************************************ *
       ***************************************  增  ***************************************
    * ************************************************************************************* */

    public void save() {
        /*
        if (existed()) {
            Shift.fatal(BasicRestStatus.repeatDataErrorStatus);
        }
        */
        getTraceTrajectoryRepository().insert(this);
    }

    public static void saveByThreePoint(TraceThreePoint... traceThreePoints) {
        if (null != traceThreePoints && traceThreePoints.length > 0) {
            for (TraceThreePoint traceThreePoint : traceThreePoints) {
                saveByThreePoint(traceThreePoint);
            }
        }
    }

    public static void saveByThreePoint(List<TraceThreePoint> list) {
        if (null != list && list.size() > 0) {
            for (TraceThreePoint traceThreePoint : list) {
                saveByThreePoint(traceThreePoint);
            }
        }
    }

    public static void saveByThreePoint(final TraceThreePoint traceThreePoint) {
        if (null == traceThreePoint.getMaxRssiApMac() || traceThreePoint.getMaxRssiApMac().length() <= 0
                || null == traceThreePoint.getMiddleRssiApMac() || traceThreePoint.getMiddleRssiApMac().length() <= 0
                || null == traceThreePoint.getMinRssiApMac() || traceThreePoint.getMinRssiApMac().length() <= 0) {
            return;
        }
        TraceCluster maxCluster = TraceCluster.selectDetailByApMac(traceThreePoint.getMaxRssiApMac());
        if(null == maxCluster){
            return;
        }
        TraceCluster middleCluster = TraceCluster.selectDetailByApMac(traceThreePoint.getMiddleRssiApMac());
        if(null == middleCluster){
            return;
        }
        TraceCluster minCluster = TraceCluster.selectDetailByApMac(traceThreePoint.getMinRssiApMac());
        if(null == minCluster){
            return;
        }
        Point center1 = new Point(Double.parseDouble(maxCluster.getLongtitude()), Double.parseDouble(maxCluster.getLatitude()));
        Point center2 = new Point(Double.parseDouble(middleCluster.getLongtitude()), Double.parseDouble(middleCluster.getLatitude()));
        Point center3 = new Point(Double.parseDouble(minCluster.getLongtitude()), Double.parseDouble(minCluster.getLatitude()));
        Point point = GeometryUtils.getPosition(
                center1, traceThreePoint.getMaxRssi(),
                center2, traceThreePoint.getMiddleRssi(),
                center3, traceThreePoint.getMinRssi());
        if (null != point) {
            TraceTrajectory trajectory = findExistedByDate(
                    traceThreePoint.getUserMac(),
                    traceThreePoint.getDate(),
                    traceThreePoint.getTime());
            boolean isNew = false;
            if (null == trajectory) {
                trajectory = new TraceTrajectory() ;
                trajectory.setUserMac(traceThreePoint.getUserMac());
                trajectory.setDate(traceThreePoint.getDate());
                trajectory.setDate(traceThreePoint.getTime());
                isNew = true;
            }
            trajectory.setXYroute(point.getX() + ";" + point.getY());
            if (isNew) {
                trajectory.save();
            } else {
                trajectory.update();
            }

        }
    }

    /* ************************************************************************************ *
       ***************************************  删  ***************************************
    * ************************************************************************************* */

    /**
     * 根据ID删除组件<br>
     * 同时删除所有的组件参数、组件内元件参数
     *
     * @param id
     */
    public static void deleteById(Integer id) {
        if (null == id) {
            Shift.fatal(BasicRestStatus.paramNullErrorStatus);
        }
        getTraceTrajectoryRepository().deleteByPrimaryKey(id);
    }

    /* ************************************************************************************ *
       ***************************************  改  ***************************************
    * ************************************************************************************* */

    /**
     * 根据Id，更新TraceTrajectory
     *
     * @param
     * @return
     */
    public void update() {
        getTraceTrajectoryRepository().updateByPrimaryKeySelective(this);
    }

    /* ************************************************************************************ *
       ***************************************  查  ***************************************
    * ************************************************************************************* */

    /**
     * 根据主键ID查询TraceTrajectory
     * @param id
     * @return
     */
    /*
    public static TraceTrajectory selectDetailById(int id) {
        TraceTrajectory entity = getTraceTrajectoryRepository().selectByPrimaryKey(id);
        return entity;
    }
    */

    /**
     * 根据查询条件查询分页列表
     *
     * @param page
     * @return
     */

    public PageResult<TraceTrajectory> selectPageByQuery(PageResult page) {
    /*
        TraceTrajectoryPageQueryDTO dto = new TraceTrajectoryPageQueryDTO();
        // TODO 设置dto参数
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        PageInfo<TraceTrajectory> pageInfo = new PageInfo<>(getTraceTrajectoryRepository().selectPageByQuery(dto));
        page.setTotal(pageInfo.getTotal());
        page.setPageData(pageInfo.getList());
        return page;
    */
        return null;
    }


}